package com.alibaba.cirtus.ots.application.app.ability.facade.v2serviceimpl;

import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.crforecastsales.domian.forecastorderline.model.ForecastOrderLine;
import com.epoch.app.crforecastsales.domian.forecastorderline.service.ForecastOrderLineService;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.otsapplicationappsdk.planorderlist.dto.AsyncRequest;
import com.epoch.app.otsapplicationappsdk.planorderlist.dto.RenderRequest;
import com.epoch.app.otsapplicationappsdk.planorderlist.service.PlanOrderListService;
import com.epoch.app.crforecastsales.model.dto.PageQueryForecastRequest;
import com.epoch.app.crforecastsales.model.dto.QueryForecastListResponse;
import com.epoch.app.crforecastsales.otsforecastorderquery.service.OtsForecastOrderQueryService;
import com.epoch.app.crforecastsales.service.ApiService;
import com.epoch.app.crplatformenhance.model.dto.QueryEnumValuesRequest;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class PlanOrderListV2ServiceImpl implements PlanOrderListService {
    public static final String PATTERN_DATE_TIME_MIDDLE_LINE = "yyyy.MM.dd";
    public static final String PATTERN_DATE_TIME = "yyyy-MM-dd HH:mm:ss";

    private static Log log = Log.getLogger(PlanOrderListV2ServiceImpl.class);
   /* @Autowired
    @Qualifier("forecastOrderQueryServiceImpl")
    private ForecastOrderQueryService forecastOrderQueryService;*/

//    @Autowired
//    private OtsPlatformEnhanceService otsPlatformEnhanceService;
    @Autowired
    private CrPlatformEnhanceService otsPlatformEnhanceService;
    @Autowired
    private ApiService apiService;

    @Autowired
    private OtsForecastOrderQueryService orderQueryService;

    @Autowired
    private ForecastOrderLineService forecastOrderLineService;

    @Override
    public Object render(RenderRequest renderRequest) {
        PageQueryForecastRequest pageQueryForecastRequest = new PageQueryForecastRequest();
        //BeanUtils.copyProperties(renderRequest,pageQueryForecastLineRequest);
        if (null == renderRequest.getCurrentPage()) {
            renderRequest.setCurrentPage(1);
        }

        if (null == renderRequest.getSize()) {
            renderRequest.setSize(10);
        }
        Integer currentPage = renderRequest.getCurrentPage();
        Integer size = renderRequest.getSize();
        Integer start = (currentPage - 1) * size;
        pageQueryForecastRequest.setLimit(size);
        pageQueryForecastRequest.setStart(start);
        List<Integer> statusList = Arrays.asList(1, 2, 3,4,5,120);
        pageQueryForecastRequest.setMainStatusList(statusList);
        // todo 等待后端接口增加statusList的入参
       // List<Integer> statusList = renderRequest.getStatusList();
        pageQueryForecastRequest.setMainStatusList(statusList);

        log.info("render of planOrder query input request {}", JSONObject.toJSONString(pageQueryForecastRequest));
       // Result<List<ForecastOrderSDO>> listResult = orderQueryService.queryForecastOrderList(pageQueryForecastRequest);
        QueryForecastListResponse listResult = apiService.queryForecastList(pageQueryForecastRequest);

        log.info("----"+JSONObject.toJSONString(listResult));
        //单据类型
        List<Info> orderTypeList = JSONObject.parseObject(JSONObject.parseObject(JSONObject.toJSONString(otsPlatformEnhanceService.queryEnumValues(new QueryEnumValuesRequest() {{
            setCode("forecastTag");
        }}))).getString("result"), List.class);

        Map<String, Object> backs = new HashMap<>();
        backs.put("list", buildData(listResult));
        backs.put("total", new Double(Math.ceil((double) listResult.getTotal() / size)).intValue());
        backs.put("page", currentPage);
        backs.put("size", size);
        backs.put("planOrderTypeList", Objects.isNull(orderTypeList) ? new ArrayList<>() : orderTypeList);

        return Result.success(backs);
    }

    @Override
    public Object async(AsyncRequest asyncRequest) {
        log.info(JSONObject.toJSONString(asyncRequest));
        //筛选条件
        List<String> gmtCreate=new ArrayList<>();
        List<String> orderType = new ArrayList<>();

        //下拉选中
        String address = null;
        String customer = null;

        //输入的单号
        String orderId = null;

        //分页参数
        Integer currentPage = 1;
        Integer pageSize = 10;

        //TAB页切换
        Integer status = null;

        JSONObject requestInput = JSONObject.parseObject(JSONObject.toJSONString(asyncRequest.getRequestInput())).getJSONObject("fields").getJSONObject("otherFields");
        log.info(JSONObject.toJSONString(asyncRequest.getRequestInput()));

        //筛选条件 日期筛选和单据类型筛选
        if (Objects.nonNull(requestInput.getJSONObject("filterOptions"))) {
            List<Group> groups = requestInput.getJSONObject("filterOptions").getJSONArray("group").toJavaList(Group.class);
            for (Group group : groups) {
                if ("date".equalsIgnoreCase(group.getType())) {
                    List<DataSource> dataSource = group.getDataSource();
                    for (DataSource source : dataSource) {
                        if ("startTime".equalsIgnoreCase(source.getKey())) {
                            gmtCreate.add(0,getStringDate(source.getValue()));
                        }
                        if ("endTime".equalsIgnoreCase(source.getKey())) {
                            gmtCreate.add(getStringDate((Objects.nonNull(source.getValue())&&StringUtils.isNotBlank(source.getValue()))?String.valueOf(Long.valueOf(source.getValue())+86399999l):""));
                        }
                    }

                }

                if ("tag".equalsIgnoreCase(group.getType())) {

                    List<DataSource> dataSource = group.getDataSource();
                    for (DataSource source : dataSource) {
                        if (source.getSelected() && !"ALL".equalsIgnoreCase(source.getValue())) {
                            orderType.add(source.getValue());
                        }
                    }

                }

            }
        }
        //判断客户或者地址是否被选中
        if (Objects.nonNull(requestInput.getJSONArray("selectOptions"))) {
            List<Group> selectOptions = requestInput.getJSONArray("selectOptions").toJavaList(Group.class);
            for (Group selectOption : selectOptions) {
                if ("address".equalsIgnoreCase(selectOption.getKey())) {
                    JSONObject selected = selectOption.getSelected();
                    if (Objects.nonNull(selected)) {
                        address = selected.getString("addressCode");
                    }

                }
                if ("customer".equalsIgnoreCase(selectOption.getKey())) {
                    JSONObject selected = selectOption.getSelected();
                    if (Objects.nonNull(selected)) {
                        customer = selected.getString("code");
                    }

                }
            }
        }

        //订单id
        if (Objects.nonNull(requestInput.getString("orderId")))
            orderId = requestInput.getString("orderId");


        //分页
        if (Objects.nonNull(requestInput.getInteger("currentPage")))
            currentPage = requestInput.getInteger("currentPage");

        if (Objects.nonNull(requestInput.getInteger("pageSize")))
            pageSize = requestInput.getInteger("pageSize");

        //切换tab
        if (Objects.nonNull(requestInput.getInteger("status")) && 0 != requestInput.getInteger("status"))
            status = requestInput.getInteger("status");


        Integer start = (currentPage - 1) * pageSize;
        PageQueryForecastRequest pageQueryForecastRequest = new PageQueryForecastRequest();
        pageQueryForecastRequest.setLimit(pageSize);
        pageQueryForecastRequest.setStart(start);

        //
        if (Objects.nonNull(status) && 0 != status) {
            pageQueryForecastRequest.setMainStatusList(Arrays.asList(status));
        } else {
            List<Integer> statusList = Arrays.asList(1, 2, 3,4,5,120);
            status = 0;
            pageQueryForecastRequest.setMainStatusList(statusList);
        }

        if (StringUtils.isNotBlank(address)) {
            pageQueryForecastRequest.setReceiveAddressCode(address);
        }

        if (CollectionUtils.isNotEmpty(orderType)) {
            pageQueryForecastRequest.setOrderTypeList(orderType);
        }

        if (StringUtils.isNotBlank(orderId)) {
            pageQueryForecastRequest.setOrderBizId(orderId);
        }

        if (StringUtils.isNotBlank(customer)) {
            pageQueryForecastRequest.setCustomerCode(customer);
        }


        if (Objects.nonNull(gmtCreate)&&CollectionUtils.isNotEmpty(gmtCreate)) {
            pageQueryForecastRequest.setGmtCreate(gmtCreate);
        }

        log.info("async pageQueryForecastRequest:"+JSONObject.toJSONString(pageQueryForecastRequest));
       // Result<List<ForecastOrderSDO>> listResult = orderQueryService.queryForecastOrderList(pageQueryForecastRequest);
        QueryForecastListResponse listResult = apiService.queryForecastList(pageQueryForecastRequest);
        //单据类型
        List<Info> orderTypeList = JSONObject.parseObject(JSONObject.parseObject(JSONObject.toJSONString(otsPlatformEnhanceService.queryEnumValues(new QueryEnumValuesRequest() {{
            setCode("forecastTag");
        }}))).getString("result"), List.class);

        Map<String, Object> backs = new HashMap<>();
        backs.put("status", status);
        backs.put("list", buildData(listResult));
        backs.put("total", new Double(Math.ceil((double) listResult.getTotal() / pageSize)).intValue());
        backs.put("page", currentPage);
        if (currentPage > 1) {
            backs.put("reload", false);
        } else {
            backs.put("reload", true);
        }
        backs.put("size", pageSize);
        backs.put("planOrderTypeList", Objects.isNull(orderTypeList) ? new ArrayList<>() : orderTypeList);

        log.info(JSONObject.toJSONString(backs));
        return Result.success(backs);
    }


    private List buildData(QueryForecastListResponse queryForecastListResponse) {
        List list = new ArrayList();
        try {
            if (CollectionUtils.isNotEmpty(queryForecastListResponse.getResult())) {
                for (Object forecastObj : queryForecastListResponse.getResult()) {
                    JSONObject forecastJson = JSONObject.parseObject(JSONObject.toJSONString(forecastObj));
                    //在原来完全拒绝基础上 判断实际回复数量是否大于0
                    if (forecastJson.getIntValue("refuseStatus") == 2 ) {
                        String orderId = forecastJson.getString("id");
                        ForecastOrderLine forecastOrderLine = new ForecastOrderLine();
                        forecastOrderLine.setMainOrderId(orderId);
                        Result<List<ForecastOrderLine>> listResult = forecastOrderLineService.loadForecastOrderLineList(forecastOrderLine);
                        int actualTotalReplyAmount = 0;
                        if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())) {
                            for (ForecastOrderLine line : listResult.getResult()) {
                                actualTotalReplyAmount = actualTotalReplyAmount + (line.getActualTotalReplyAmount() != null ? line.getActualTotalReplyAmount() : 0);
                            }
                        }
                        if (actualTotalReplyAmount != 0) {
                            forecastJson.put("refuseStatus",1);
                        }
                    }
                    list.add(forecastJson);
                }
            }
            return list;
        } catch (Exception e) {
            log.info("预报销售订单列表拒绝状态解析异常",e);
        }
        return list;
    }

    private String getStringDate(String timestamp){

        if (StringUtils.isBlank(timestamp)){
            return null;
        }
        Date date = new Date(Long.valueOf(timestamp));
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat(PATTERN_DATE_TIME);
        String format = simpleDateFormat.format(date);

        return format;
    }

    @Data
    static class Group {
        @JsonProperty("type")
        public String type;

        @JsonProperty("title")
        public String title;

        @JsonProperty("placeholder")
        public String placeholder;

        @JsonProperty("key")
        public String key;

        @JsonProperty("selected")
        public JSONObject selected;


        @JsonProperty("fetchUrl")
        public String fetchUrl;

        @JsonProperty("dataSource")
        public List<DataSource> dataSource;


    }

    @Data
    static class SelectOption {
        @JsonProperty("type")
        public String type;

        @JsonProperty("title")
        public String title;

        @JsonProperty("placeholder")
        public String placeholder;

        @JsonProperty("dataSource")
        public List<DataSource> dataSource;

    }

    @Data
    static class DataSource {
        @JsonProperty("label")
        public String label;

        @JsonProperty("key")
        public String key;

        @JsonProperty("value")
        public String value;

        @JsonProperty("selected")
        public Boolean selected;

    }
    @Data
    public static class Info{
        private String label;
        private String value;
    }
}
